<template>
    <div class="team-detail-page">
        <!-- 团队信息模块 -->
        <el-card class="team-info-card">
            <div class="flex">
                <div class="blue-radius"></div>
                <h2 class="page-title">我管理的团队详情</h2>
            </div>
            <div class="info-content">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <div class="info-item">
                            <label>团队编号：</label>
                            <span>{{ teamInfo._id }}</span>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="info-item">
                            <label>团队名称：</label>
                            <span>{{ teamInfo.name }}</span>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="info-item">
                            <label>团队头像：</label>
                            <el-avatar :src="teamInfo.avatar" size="default"></el-avatar>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="info-item">
                            <label>团队标签：</label>
                            <el-tag v-for="tag in teamInfo.tagIds" :key="teamInfo.tagIds._id"
                                :type="tag.name == '高血压' ? 'danger' : 'success'">
                                {{ tag.name }}
                            </el-tag>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20" style="margin-top: 16px;">
                    <el-col :span="12">
                        <div class="info-item">
                            <label>机构地址：</label>
                            <span>{{ teamInfo.organizationId?.address }}</span>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="info-item-rate">
                            <label>团队评分：</label>
                            <el-rate v-model="(teamInfo.rate)" disabled allow-half show-score
                                text-color="#ff9900"></el-rate>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <div class="info-item">
                            <label>签约人数：</label>
                            <span>{{ teamInfo.signNumber }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20" style="margin-top: 16px;">
                    <el-col :span="12">
                        <div class="info-item">
                            <label>联系人号码：</label>
                            <span>{{ teamInfo.leaderId?.phone }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-item">
                            <label>创建人：</label>
                            <span>{{ teamInfo.leaderId?.name }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20" style="margin-top: 16px;">
                    <el-col :span="6">
                        <div class="info-item">
                            <label>团队状态：</label>
                            <el-switch v-model="teamInfo.state" active-text="启用" inactive-text="停用" inline-prompt />
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-card>

        <!-- 团队成员模块 -->
        <el-card class="member-card" style="margin-top: 20px;">
            <template #header>
                <div class="card-header">团队成员 ({{ teamMembers.length }})</div>
            </template>
            <el-row :gutter="20">
                <el-col :span="6" v-for="(member, idx) in teamMembers" :key="idx">
                    <el-card class="member-item">
                        <!-- 头像 -->
                        <div class="member-avatar" :style="{
                            backgroundImage: `url(${member.avatar})`,
                            backgroundSize: 'cover',
                            backgroundPosition: 'center'
                        }">
                        </div>
                        <div class="member-header">
                            <p>医生姓名：{{ member.name }}</p>
                            <!-- 后端没有isLeader数据 -->
                            <el-tag v-if="member.isLeader" type="warning" size="small">团队长</el-tag>
                        </div>

                        <div class="member-info">
                            <p>职称：{{ member.roleId?.name }}</p>
                            <p>电话：{{ member.phone }}</p>
                            <p>医生简介：
                                {{ member.roleId?.intro ? (member.roleId.intro.length > 10 ?
                                    member.roleId.intro.slice(0, 10) + '...'
                                    : member.roleId.intro) : '暂无' }}
                            </p>
                        </div>
                        <div class="member-action">
                            <el-button type="text" @click="viewDoctorDetail(member._id)">医师详情</el-button>
                            <el-button type="text" style="color: #ff4d4f !important;" @click="removeMember(member._id)"
                                :disabled="member.isLeader">
                                移除队员
                            </el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>


        <!-- 服务包模块 -->
        <el-card class="service-card" style="margin-top: 20px;">
            <div class="card-header" style="margin-bottom: 20px;">服务包 ({{ servicePackages.length }})</div>
            <el-row>
                <el-col :span="8" v-for="pkg in servicePackages" :key="pkg._id">
                    <el-card style="margin-inline: 25px;margin-bottom: 20px;">
                        <div class="flex-around">
                            <!-- 头像 -->
                            <div class="member-avatar" :style="{
                                backgroundImage: `url(${pkg.image})`,
                                backgroundSize: 'cover',
                                backgroundPosition: 'center'
                            }">
                            </div>
                            <div>
                                <div class="pkg-header">
                                    <span>{{ pkg.name }}</span>
                                </div>
                                <div class="pkg-info">
                                    <p>服务对象：所有人</p>
                                </div>
                            </div>
                        </div>

                        <div class="pkg-action flex-between">
                            <div class="triangle-box" :class="{ active: pkg.state === 1, inactive: pkg.state === 0 }">
                            </div>
                            <div class="triangle-box-small"
                                :class="{ active: pkg.state === 1, inactive: pkg.state === 0 }">
                            </div>
                            <div class="service-state" :class="{ active: pkg.state === 1, inactive: pkg.state === 0 }">
                                {{ pkg.state === 1 ? '使用中' : '已停用' }}
                            </div>
                            <el-button type="text" @click="viewPackageDetail(pkg._id)">服务包详情</el-button>
                        </div>
                    </el-card>
                </el-col>
                <!-- 添加服务包按钮 -->
                <el-col :span="7">
                    <el-card class="service-item add-pkg" @click="openServicePackModal">
                        <div class="add-icon">
                            <i class="el-icon-plus">+</i>
                            <p>添加服务包</p>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>


        <!-- 加入团队申请模块 -->
        <el-card class="apply-card" style="margin-top: 20px;">
            <template #header>
                <div class="card-header">加入团队申请</div>
            </template>
            <el-row :gutter="20">
                <el-col :span="8" v-for="app in joinApplications" :key="app._id">
                    <el-card class="apply-item">
                        <div class="app-info">
                            <!-- 头像 -->
                            <div class="member-avatar" :style="{
                                backgroundImage: `url(${app.applicantId?.avatar})`,
                                backgroundSize: 'cover',
                                backgroundPosition: 'center'
                            }">
                            </div>

                            <div class="app-person">
                                <span class="app-name">医生姓名：{{ app.applicantId?.name }}</span>
                                <span class="app-id">{{ app.applicantId?.roleId?._id }}</span>
                            </div>

                            <p>联系电话：{{ app.applicantId?.phone }}</p>

                            <!-- 申请时间和状态标签 -->
                            <div class="app-status-row">
                                <p>申请时间：{{ app.applyTime }}</p>
                                <!-- 状态标签：根据state显示不同文本和样式 -->
                                <el-tag :type="app.state === 0 ? 'danger' : app.state === 1 ? 'info' : 'success'"
                                    class="status-tag">
                                    {{ app.state === 0 ? '已拒绝' : app.state === 1 ? '待审核' : '已通过' }}
                                </el-tag>
                            </div>
                        </div>

                        <!-- 操作按钮） -->
                        <div class="app-action">
                            <el-button type="primary" size="small" @click="approveApply(app)"
                                :disabled="app.state !== 1">
                                通过
                            </el-button>
                            <el-button type="danger" size="small" @click="rejectApply(app)" :disabled="app.state !== 1">
                                拒绝
                            </el-button>
                            <el-button type="text" size="small" @click="viewDoctorDetail(app.applicantId?._id)">
                                医师详情
                            </el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>




        <!-- 底部操作按钮 -->
        <div class="action-bar" style="margin-top: 20px;">
            <el-row :gutter="20">
                <el-col :span="2">
                    <el-button type="primary" @click="editTeam">编辑团队</el-button>
                </el-col>
                <el-col :span="2">
                    <el-button type="danger" @click="deleteTeam">解散团队</el-button>
                </el-col>
                <el-col :span="2">
                    <el-button type="default" onclick="history.back()">返回</el-button>
                </el-col>
            </el-row>
        </div>
    </div>

    <!-- 编辑团队弹窗（子组件） -->
    <TeamUpdate v-model:visible="dialogVisible" :team-info="{
        teamName: teamInfo.value?.name,
        avatar: teamInfo.value?.avatar,
        orgId: teamInfo.value?.organizationId?._id,
        tags: teamInfo.value?.tagIds.map(tag => tag._id)
    }" :org-options="orgOptions" :tag-options="tagOptions" @save="handleSave" />


    <TeamServicePackAdd :visible="isServicePackModalVisible" @close="closeServicePackModal"
        @confirm="handleServicePackConfirm" />
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { detailTeamsApi, dropoutTeamsApi, removeTeamsApi, UpdateTeamApplyApi, updateTeamsApi } from '../../api/teamManage'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import TeamServicePackAdd from './TeamServicePackAdd.vue'
import TeamUpdate from './TeamUpdate.vue'


const route = useRoute()
const router = useRouter()

// 团队信息
const teamInfo = ref({})
// 团队成员
const teamMembers = ref([])
// 服务包
const servicePackages = ref([])
// 加入团队申请
const joinApplications = ref([])
// 编辑弹窗显示状态
const dialogVisible = ref(false)


// 所属机构下拉选项
const orgOptions = ref([
    // { label: '洛西社区卫生服务站', value: 'luoxi' },
])

// 团队标签下拉选项
const tagOptions = ref([
    { label: '高血压', value: '67c90bff35738d92907c1454' },
    { label: '低血糖', value: '67cfaeb34786f92b365536b5' },
    { label: '冠心病', value: '67cfaec04786f92b365536b7' },
    { label: '心律不齐', value: '686f67db5a2300006e007fb4' },
    { label: '高胆固醇', value: '67c90c0635738d92907c1458' },
])

// 打开编辑弹窗
const editTeam = () => {
    dialogVisible.value = true
}

// 保存团队信息
const handleSave = async (formData) => {
    console.log('提交的表单数据：', formData)
    try {
        //构造更新参数
        const updateParams = {
            _id: teamInfo.value._id, // 当前团队ID（必传，用于定位要修改的团队）
            name: formData.name, // 团队名称
            avatar: formData.avatar, // 团队头像
            organizationId: formData._id, // 所属机构ID（表单的_id对应机构ID）
            tagIds: formData.tags // 团队标签ID数组
        };

        //调用更新接口
        const res = await updateTeamsApi(updateParams);

        //处理接口响应
        if (res.code === 200) {
            ElMessage.success('团队信息修改成功');
            dialogVisible.value = false; // 关闭编辑弹窗
            searchTeamsDetail(); // 重新加载团队详情，刷新页面显示
        } else {
            ElMessage.error(res.message || '修改失败，请重试');
        }
    } catch (err) {
        ElMessage.error('未知错误');
    }
}


//查看服务包详情
const viewPackageDetail = (pkg_id) => {
    router.push(`/data/servicePack/detail/${pkg_id}`)
}

// 添加服务包
// 控制子组件弹窗的显示状态
const isServicePackModalVisible = ref(false);

// 打开弹窗
const openServicePackModal = () => {
    isServicePackModalVisible.value = true;
};

// 关闭弹窗（子组件触发时调用）
const closeServicePackModal = () => {
    isServicePackModalVisible.value = false;
};

// 添加服务包
const handleServicePackConfirm = async (selectedServicePacks) => {
    try {
        //本地去重添加
        selectedServicePacks.forEach(newPkg => {
            const isExists = servicePackages.value.some(existPkg => existPkg._id === newPkg._id);
            if (!isExists) {
                servicePackages.value.push(newPkg);
            }
        });

        // 构造更新参数（包含团队ID和所有关键字段，避免后端覆盖为空）
        const updateParams = {
            _id: teamInfo.value._id, // 团队ID
            name: teamInfo.value.name, // 保留原有团队名称
            avatar: teamInfo.value.avatar, // 保留原有团队头像
            organizationId: teamInfo.value.organizationId?._id, // 保留原有机构ID
            tagIds: teamInfo.value.tagIds.map(tag => tag._id), // 保留原有标签ID
            servicePackIds: servicePackages.value.map(pkg => pkg._id) // 新的服务包ID列表
        };

        // 调用团队更新接口
        const res = await updateTeamsApi(updateParams);
        if (res.code === 200) {
            ElMessage.success('服务包添加成功');
            closeServicePackModal(); // 关闭弹窗
        } else {
            // 失败
            selectedServicePacks.forEach(newPkg => {
                servicePackages.value = servicePackages.value.filter(pkg => pkg._id !== newPkg._id);
            });
            ElMessage.error(res.message || '服务包添加失败，请重试');
        }
    } catch (err) {
        // 网络错误
        selectedServicePacks.forEach(newPkg => {
            servicePackages.value = servicePackages.value.filter(pkg => pkg._id !== newPkg._id);
        });
        ElMessage.error('网络异常，添加失败');
    }
};

// 同意申请
const approveApply = async (apply) => {
    try {
        apply.state = 2; // 设置状态为“通过”
        await UpdateTeamApplyApi(apply);
        ElMessage.success('审批通过，成员已加入团队！');
        searchTeamsDetail();
    } catch (error) {
        ElMessage.error('审批失败：' + error.message);
    }
};

// 拒绝申请
const rejectApply = async (apply) => {
    try {
        apply.state = 0;
        await UpdateTeamApplyApi(apply);
        ElMessage.error('已拒绝申请！');

    } catch (error) {
        ElMessage.error('拒绝失败：' + error.message);
    }
};

//查看医师详情
const viewDoctorDetail = (doctor_id) => {
    router.push(`/data/doctor/detail/${doctor_id}`)
}

//移除团队成员
const removeMember = async (memberId) => {
    try {
        console.log('团队ID:', teamInfo.value?._id);
        console.log('医生ID:', memberId);
        // 二次确认
        await ElMessageBox.confirm(
            '确定要移除该队员吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        // 调用移除接口
        const res = await dropoutTeamsApi({
            doctorId: memberId, // 传入memberId，即医生的_id
            teamId: teamInfo.value._id, // 团队ID
        })

        if (res.code === 200) {
            ElMessage.success('队员已成功移除')
            // 本地更新成员列表
            teamMembers.value = teamMembers.value.filter(member => member._id !== memberId)
        } else {
            ElMessage.error(res.message || '移除失败，请重试')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败：' + (error.message || '网络异常'))
        }
    }
}

/// 解散团队（删除功能）
async function deleteTeam() {
    // 校验：确保团队信息已加载，避免_id不存在
    if (!teamInfo.value?._id) {
        ElMessage.error('团队信息加载失败，无法执行删除操作')
        return
    }

    try {
        // 弹框确认（二次确认防止误操作）
        await ElMessageBox.confirm(
            '此操作将永久删除此团队，删除后不可恢复，是否继续?',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        // 调用删除团队的API，传递当前团队的_id
        const res = await removeTeamsApi({
            _id: teamInfo.value._id // 从团队详情中获取当前团队的_id
        })
        if (res.code === 200) {
            ElMessage.success('团队已成功解散')
            // 删除成功后跳转
            router.push('/data/team/list')
        } else {
            ElMessage.error(res.message || '解散团队失败，请重试')
        }
    } catch (error) {
        // 若用户取消确认，提示操作取消
        if (error === 'cancel') {
            ElMessage.info('已取消解散操作')
        } else {
            // 其他错误
            ElMessage.error('操作失败，请稍后重试')
        }
    }
}

// 页面初始化，加载团队信息
onMounted(async () => {
    searchTeamsDetail()
})


// 获取一个团队详情
function searchTeamsDetail() {
    detailTeamsApi({
        // 这里传团队的_id
        _id: route.params._id
    })
        .then(res => {
            if (res.code == 200) {
                console.log(res.data);
                teamInfo.value = res.data
                teamMembers.value = res.data.memberIds
                servicePackages.value = res.data.servicePackIds
                joinApplications.value = res.data.teamApply
            }
        })
}



</script>

<style scoped>
.page-title {
    margin: 0 0 16px;
    font-size: 18px;
    font-weight: 550;
    color: #333333E5;
}

.blue-radius {
    border-width: 0px;
    width: 6px;
    height: 20px;
    background: inherit;
    background-color: rgba(41, 132, 248, 1);
    border: none;
    border-radius: 8px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    margin-top: 4px;
    margin-right: 10px;
}

.team-detail-page {
    padding: 20px;
}

.card-header {
    font-size: 16px;
    font-weight: bold;
}

/* 团队信息模块 */
.team-info-card .info-content {
    padding: 16px;
    border-top: 1px solid #f5f7fa;
}

.info-item {
    margin-bottom: 8px;
    font-size: 13px;
    display: flex;
}

.info-item-rate {
    margin-bottom: 8px;
    font-size: 13px;
}

.member-action {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #f5f7fa;
}

/* 服务包模块 */
.service-card {
    height: 100%;
}

.service-item {
    height: 73%;
}

.pkg-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 16px;
    font-weight: 500;
}

.pkg-info {
    margin-bottom: 16px;
    font-size: 12px;
    color: #999999;
}

.pkg-action {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #f5f7fa;
}

/* 服务包模块 - 核心修改 */
/* 为每个服务包卡片添加相对定位，作为角标父容器 */
.service-card .el-card {
    position: relative;
    /* 关键：让角标以当前卡片为参考 */
}

/* 右上角角标定位 */
.triangle-box {
    width: 60px;
    height: 60px;
    background: var(--el-color-primary);
    clip-path: polygon(100% 0, 100% 100%, 0 100%);
    transform: rotate(270deg);
    position: absolute;
    right: 0;
    /* 相对于卡片右侧定位 */
    top: 0;
    /* 相对于卡片顶部定位 */
}

.triangle-box-small {
    width: 20px;
    height: 20px;
    background: #fff;
    clip-path: polygon(100% 0, 100% 100%, 0 100%);
    transform: rotate(270deg);
    position: absolute;
    right: 0;
    /* 相对于卡片右侧定位 */
    top: 0;
    /* 相对于卡片顶部定位 */
}

.service-state {
    font-size: 12px;
    font-weight: 500;
    color: #ffffff;
    position: absolute;
    right: 3px;
    /* 向右微调，适配文字显示 */
    top: 12px;
    transform: rotate(44deg);
}

/*服务包内容区域样式（避免被角标遮挡） */
.service-card .el-card__body {
    padding: 15px;
    /* 增加内边距，避免内容被角标遮挡 */
}

/* 角标主背景（使用中为蓝色，已停用为红色） */
.triangle-box.active {
    background: var(--el-color-primary);
    /* 蓝色 */
}

.triangle-box.inactive {
    background: #ff4d4f;
    /* 红色 */
}

/* 角标内小三角（使用中为白色，已停用为红色） */
.triangle-box-small.active {
    background: #fff;
}

.service-state.active {
    color: #fff;
    /* 使用中保持白色 */
}


/* 添加服务包卡片核心样式 */
.add-pkg {
    margin-left: 25px;
    cursor: pointer;
    text-align: center;
    padding: 20px 0;
    background-color: #f8fafc;
    /* 浅蓝背景，匹配设计图 */
    transition: background-color 0.3s ease;
    /* 平滑过渡 */
}

/* hover时背景加深 */
.add-pkg:hover {
    background-color: #e6f2fa;
}

/* 图标和文字容器（垂直居中） */
.add-icon {
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 加号图标样式 */
.add-icon i {
    font-size: 40px;
    color: #87cefa;
}

/* 文字样式 */
.add-icon p {
    margin-top: 8px;
    color: #87cefa;
    font-size: 14px;
}


/* 加入申请模块 */
.el-col-8,
.el-col-8.is-guttered {
    margin-bottom: 20px;
}

.apply-card .apply-item {
    height: 100%;
}

.app-person {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.app-name {
    margin-top: 20px;
    font-size: 15px;
    font-weight: 500;
}

.app-id {
    margin-top: 20px;
    font-size: 12px;
    color: #999999;
}

.app-action {
    text-align: right;
    margin-top: 8px;
}

/* 团队成员模块 */
.member-info {
    font-size: 13px;
}

.member-item {
    display: flex;
}

.member-header>p {
    font-size: 15px;
    font-weight: 600;
}

.member-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
}

.el-col-6,
.el-col-6.is-guttered {
    margin-bottom: 20px;
}
</style>